package com.example.zx.theline.lyjh.lyyjh;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.zx.theline.pub.CheckInfoActivity;
import com.example.zx.theline.lyjh.pub.JhshCKActivity;
import com.example.zx.theline.lyjh.lyyjh.pub.JhshShActivity;
import com.example.zx.theline.R;
import com.example.zx.theline.lyjh.pub.JhshXmzgbmShActivity;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;
import com.scu.miomin.shswiperefresh.view.SHListView;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.ShyjhxqBean;
import Utils.BackHandlerHelper;
import Utils.DateUtil;
import Utils.MyToast;
import Utils.StatusUtil;
import app.MyApplication;
import base.BaseFragment;
import GsonBean.JhshBean;
import bean.JhshSearchBean;
import network.BaseCallBack;
import network.NetWorkApi;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.JhshSearchView;

/**
 * A simple {@link Fragment} subclass.
 * 计划审核月计划
 */
public class JhshyjhFragment extends BaseFragment implements View.OnClickListener, SHSwipeRefreshLayout.SHSOnRefreshListener {
    public static GsonBean.ShyjhxqBean ZsyjhxxShBean;
    //UI
    private SHSwipeRefreshLayout mSHSwipeRefreshLayout;
    private MyAdapter mSHListViewAdapter;
    private SHListView mSHListView;
    private TextView mFootTextView;

    //head按钮
    private TextView leftTextView,prev,centerTextView, next,rightTextView;

    private JhshSearchView mJhshSearchView;
    //Data
    private int pageNumber = 0;
    private JhshBean mJhshBean;
    private JhshSearchBean mSearchBean;
    List<JhshBean.RowsBean> list;

    public static boolean onStartRefresh = false;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_jhshyjh, container, false);

        mSHSwipeRefreshLayout = (SHSwipeRefreshLayout) contentView.findViewById(R.id.SHSwipeRefreshLayout);
        mSHListView = (SHListView) contentView.findViewById(R.id.SHListView);
        View FootView = inflater.inflate(R.layout.refresh_view, null);
        mFootTextView = (TextView) FootView.findViewById(R.id.title);
        mSHSwipeRefreshLayout.setFooterView(FootView);

        leftTextView = (TextView) contentView.findViewById(R.id.leftTextView);
        prev = (TextView) contentView.findViewById(R.id.prev);
        centerTextView = (TextView) contentView.findViewById(R.id.centerTextView);
        next = (TextView) contentView.findViewById(R.id.next);
        rightTextView = (TextView) contentView.findViewById(R.id.rightTextView);

        mJhshSearchView = (JhshSearchView) contentView.findViewById(R.id.jhshsearchview);
        mJhshSearchView.setZtlistFlag(JhshSearchView.SHYJH);
        //初始化模块
        InitData();
        InitSearchView();
        InitListen();
        return contentView;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (onStartRefresh) {
            onRefresh();
            onStartRefresh = false;
        }
    }

    @Override
    protected void InitData() {

        list = new ArrayList<>();
        mSHListViewAdapter = new MyAdapter();
        mSHListView.setAdapter(mSHListViewAdapter);
    }


    public void InitSearchView() {

        prev.setText("上一月");
        next.setText("下一月");

        mSearchBean = new JhshSearchBean();
        if (DateUtil.compare2Time("05") < 0) { //显示当前本月计划
            mSearchBean.setJhnyks(DateUtil.getYearAndMonth(date));
            mSearchBean.setJhnyjs(DateUtil.getYearAndMonth(date));
        } else { //显示次月计划
            mSearchBean.setJhnyks(DateUtil.getYearAndMonth(DateUtil.getAfterMonthDate(date, 1)));
            mSearchBean.setJhnyjs(DateUtil.getYearAndMonth(DateUtil.getAfterMonthDate(date, 1)));
            date=DateUtil.getAfterMonthDate(date,1);
        }
//        mJhshSearchView.setDefaultDate(mSearchBean);

        // 设置searchview默认显示日期
        centerTextView.setText(DateUtil.getYearAndMonth(date));
        mJhshSearchView.setConfirmListener(new JhshSearchView.OnClick() {
            @Override
            public void onConfirmListener(JhshSearchBean Util) {
                mSearchBean = Util;
                mSHSwipeRefreshLayout.startRefresh();
                onRefresh();
            }
        });
    }

    @Override
    protected void InitListen() {
        mSHSwipeRefreshLayout.setOnRefreshListener(this);
        rightTextView.setOnClickListener(this);
        centerTextView.setOnClickListener(this);
        leftTextView.setOnClickListener(this);
        prev.setOnClickListener(this);
        next.setOnClickListener(this);
    }

    //页面第一次进入加载
    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        requestYjhshList(0, 10, "refresh");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //日期选择
            case R.id.centerTextView:
                TimePickerView.getInstanceEndMonth(getContext(),JhshyjhFragment.this.date,new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        JhshyjhFragment.this.date=date;
                        setSearchBean();
                        upDatedAndRefresh();
                        requestYjhshList(0, 10, "refresh");
                    }
                }).show();
                break;
            case R.id.leftTextView:
                getActivity().finish();
                break;
            case R.id.rightTextView:
                if (mJhshSearchView.getVisibility() == View.GONE) {
                    mJhshSearchView.setVisibility(View.VISIBLE);
                } else {
                    mJhshSearchView.setVisibility(View.GONE);
                }
                break;
            case R.id.prev:
                butPrev();
                break;
            case R.id.next:
                butNext();
                break;

        }
    }

    //按钮上个月事件
    public void butPrev() {
        date = DateUtil.getAfterMonthDate(date, -1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //按钮下个月事件
    public void butNext() {
        date = DateUtil.getAfterMonthDate(date, 1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //更新标题栏日期并刷新列表数据
    public void upDatedAndRefresh() {
        centerTextView.setText(DateUtil.getYearAndMonth(date));
        //刷新列表数据
        onRefresh();
    }

    //设置搜索日期
    private void setSearchBean() {
        mSearchBean.setJhnyks(DateUtil.getYearAndMonth(date));
        mSearchBean.setJhnyjs(DateUtil.getYearAndMonth(date));
        //将搜索数据同步更新带搜索view当中
        mJhshSearchView.setDefaultDate(mSearchBean);
    }

    @Override
    public void onRefresh() {
        requestYjhshList(0, 10, "refresh");
    }

    @Override
    public void onLoading() {
        requestYjhshList(pageNumber, 10, "loadmore");
    }

    @Override
    public void onRefreshPulStateChange(float percent, int state) {
        switch (state) {
            case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                mSHSwipeRefreshLayout.setRefreshViewText("下拉刷新");
                break;
            case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                mSHSwipeRefreshLayout.setRefreshViewText("松开刷新");
                break;
            case SHSwipeRefreshLayout.START:
                mSHSwipeRefreshLayout.setRefreshViewText("正在刷新");
                break;
        }
    }

    @Override
    public void onLoadmorePullStateChange(float percent, int state) {
        switch (state) {
            case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                mFootTextView.setText("上拉加载");
                break;
            case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                mFootTextView.setText("松开加载");
                break;
            case SHSwipeRefreshLayout.START:
                mFootTextView.setText("正在加载...");
                break;
        }
    }

    @Override
    public boolean onBackPressed() { //处理自定义View，系统返回键
        if (mJhshSearchView.getVisibility() == View.VISIBLE) {
            mJhshSearchView.setVisibility(View.GONE);
            return true;
        } else {
            return BackHandlerHelper.handleBackPress(this);
        }
    }

    //请求月计划审核列表数据
    private void requestYjhshList(int pageNum, int pageSize, final String flag) {
        this.pageNumber = pageNum;
        pageNumber++;
        Map<String,String> map=new HashMap<>();
        map.put("pageNumber", String.valueOf(pageNumber));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("loginDwId", MyApplication.getmLoginUser().getUserUnitId());
        map.put("loginDwMc", MyApplication.getmLoginUser().getUserUnitName());
        map = setMap(map, mSearchBean);

        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getSheyjh(map, new BaseCallBack<JhshBean>() {
                    @Override
                    public void Success(Call<JhshBean> call, Response<JhshBean> response) {
                        try {
                            mJhshBean = response.body();
                            if (mJhshBean.getMsg().equals("success")) {
                                if (mJhshBean.getRows().size() != 0) {
                                    if (flag.equals("refresh")) { //判断是否是刷新，如果是刷新则将之前的List清空
                                        list.clear();
                                    }
                                    list.addAll(mJhshBean.getRows()); //将请求到的数据添加到List集合中
                                    mSHListViewAdapter.notifyDataSetChanged();
                                } else {
                                    if (flag.equals("loadmore")) {
//                                        MyToast.showToast("暂无更多数据");
                                    } else {
                                        list.clear();
                                        mSHListViewAdapter.notifyDataSetChanged();
//                                        MyToast.showToast("暂无数据");
                                    }
                                }
                            } else {
                                MyToast.showNullObjectError(getContext());
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<JhshBean> call, Throwable t) {
                        MyToast.showFail();
                    }

                    @Override
                    public void onFinally() {
                        switch (flag) {
                            case "refresh": //刷新
                                mSHSwipeRefreshLayout.finishRefresh();
                                break;
                            case "loadmore": //加载
                                mSHSwipeRefreshLayout.finishLoadmore();
                                break;
                        }
                    }
                }
        );
    }

    //适配器
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            ViewHolder mViewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.zsyjhview, null);
                mViewHolder = new ViewHolder();
                mViewHolder.yjhh = (TextView) convertView.findViewById(R.id.yjhh);
                mViewHolder.sgrq = (TextView) convertView.findViewById(R.id.sgrq);
                mViewHolder.lb = (TextView) convertView.findViewById(R.id.lb);
                mViewHolder.layout_blfh = (LinearLayout) convertView.findViewById(R.id.layout_blfh);
                mViewHolder.tablelayout = (LinearLayout) convertView.findViewById(R.id.tablelayout);
                mViewHolder.xm = (TextView) convertView.findViewById(R.id.xm);
                mViewHolder.hb = (TextView) convertView.findViewById(R.id.hb);
                mViewHolder.sgdd = (TextView) convertView.findViewById(R.id.sgdd);
                mViewHolder.sgxm = (TextView) convertView.findViewById(R.id.sgxm);
                mViewHolder.sgnr = (TextView) convertView.findViewById(R.id.sgnr);
                mViewHolder.sgjx = (TextView) convertView.findViewById(R.id.sgjx);
                mViewHolder.blfh = (TextView) convertView.findViewById(R.id.blfh);
                mViewHolder.sgdw = (TextView) convertView.findViewById(R.id.sgdw);
                mViewHolder.zt = (TextView) convertView.findViewById(R.id.zt);
                mViewHolder.mImageView = (ImageView) convertView.findViewById(R.id.mImageView);
                mViewHolder.tv_jhsh = (TextView) convertView.findViewById(R.id.tv_jhsh);
                mViewHolder.flagImg = (ImageView) convertView.findViewById(R.id.yue_flag);
                mViewHolder.btnShlc = (TextView) convertView.findViewById(R.id.btn_shlc);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }
            mViewHolder.yjhh.setText(list.get(position).getBh());
            mViewHolder.sgrq.setText(list.get(position).getExsgrq());
            mViewHolder.lb.setText(list.get(position).getLb() + "类");
            if (list.get(position).getLb().equals("B")) {
                mViewHolder.lb.setTextColor(getResources().getColor(R.color.colorTextB));
            } else if (list.get(position).getLb().equals("C")) {
                mViewHolder.lb.setTextColor(getResources().getColor(R.color.colorTextC));
            }
            mViewHolder.xm.setText(list.get(position).getXlmc());
            mViewHolder.hb.setText(list.get(position).getXbmc());
            mViewHolder.sgdd.setText(list.get(position).getSgdd());
            mViewHolder.sgxm.setText(list.get(position).getXmmc());
            mViewHolder.sgnr.setText(list.get(position).getNrmc());
            mViewHolder.sgjx.setText(list.get(position).getJxmc());
            mViewHolder.blfh.setText(list.get(position).getFhcsmc());
            mViewHolder.sgdw.setText(list.get(position).getSgdwmc());
            mViewHolder.zt.setText(list.get(position).getYjhCxState());
            //根据状态标识 1 5 为红色 其余为绿色
            if(list.get(position).getYjhCxValue().equals("1")||list.get(position).getYjhCxValue().equals("5")){
                mViewHolder.zt.setTextColor(getContext().getResources().getColor(R.color.colorRed));
            } else {
                mViewHolder.zt.setTextColor(getContext().getResources().getColor(R.color.colorGreenTitle));
            }
            //B类防御 根据该计划类型是否为B类 判断是否显示
            if (list.get(position).getLb().equals("B")) {
                mViewHolder.layout_blfh.setVisibility(View.VISIBLE);
            } else {
                mViewHolder.layout_blfh.setVisibility(View.GONE);
            }


            if (MyApplication.getmLoginUser().getUserUnitName().equals(list.get(position).getSpcsmc())) {
                mViewHolder.tv_jhsh.setText("主审");
                mViewHolder.tv_jhsh.setVisibility(View.VISIBLE);
            } else {
                mViewHolder.tv_jhsh.setText("");
                mViewHolder.tv_jhsh.setVisibility(View.GONE);
            }
            //默认颜色
            mViewHolder.flagImg.setImageResource(R.drawable.yue_lv);
            //存在优化：shsftg==2
            if (list.get(position).getShsftg() != null && list.get(position).getShsftg().equals("2")) {
                mViewHolder.flagImg.setImageResource(R.drawable.yue_huang); //黄色
            }
            //重新指定：yjhSpzd==5
            if (list.get(position).getYjhSpzd() != null && list.get(position).getYjhSpzd().equals("5")) {
                mViewHolder.flagImg.setImageResource(R.drawable.yue_lan); //蓝色
            }
            //已超时：yjhCxValue==5
            if (list.get(position).getYjhCxValue() != null && list.get(position).getYjhCxValue().equals("5")) {
                mViewHolder.flagImg.setImageResource(R.drawable.yue_hong); //红色
            }

            //查看审核流程
            mViewHolder.btnShlc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CheckInfoActivity.mRowsBean = list.get(position);
                    Intent intent = new Intent(getActivity(), CheckInfoActivity.class);
                    intent.putExtra("flags", "flags");
//                    intent.putExtra("pos",position);
                    startActivity(intent);
                }
            });

            //查看详情
            mViewHolder.tablelayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,String> map=new HashMap<>();
                    map.put("jdjhbBh", list.get(position).getBh());
                    map.put("spzd", list.get(position).getYjhSpzd());
                    map.put("dwId", MyApplication.getmLoginUser().getUserUnitId());
                    MyApplication.ShowWaitDialog(getContext());
                    NetWorkApi.getShyjhDetailData(map, new Callback<ShyjhxqBean>() {
                                @Override
                                public void onResponse(Call<ShyjhxqBean> call, Response<ShyjhxqBean> response) {
                                    try {
                                        ShyjhxqBean Bean = response.body();
                                        Bean.getInfo().setYjhDwlb(list.get(position).getYjhDwlb());
                                        Bean.getInfo().setYjhCxValue(list.get(position).getYjhCxValue());

                                        //状态为：待审核 || 已超时 跳转到详情页面
                                        if (Bean.getInfo().getYjhCxValue().equals(StatusUtil.STATUS_YJH_DSH) || Bean.getInfo().getYjhCxValue().equals(StatusUtil.STATUS_YJH_YCS)) {
                                            JhshCKActivity.ZsyjhxxShBean = Bean;
                                            getContext().startActivity(new Intent(getContext(), JhshCKActivity.class));
                                        }
                                        //状态为：（可审核 || 已审批）&& yjhDwlb == "spcs"
                                        if ((Bean.getInfo().getYjhCxValue().equals(StatusUtil.STATUS_YJH_KSH) ||
                                                Bean.getInfo().getYjhCxValue().equals(StatusUtil.STATUS_YJH_YSP))
                                                && Bean.getInfo().getYjhDwlb().equals("spcs")) {
                                            JhshXmzgbmShActivity.ZsyjhxxShBean = Bean;
                                            getContext().startActivity(new Intent(getContext(), JhshXmzgbmShActivity.class));
                                        }
                                        //状态为：可审核 && yjhDwlb != "spcs"
                                        if (Bean.getInfo().getYjhCxValue().equals(StatusUtil.STATUS_YJH_KSH) && !Bean.getInfo().getYjhDwlb().equals("spcs")) {
                                            JhshShActivity.ZsyjhxxShBean = Bean;
                                            getContext().startActivity(new Intent(getContext(), JhshShActivity.class));
                                        }
                                    } catch (Exception e) {
                                        MyToast.showFail();
                                    }
                                    MyApplication.HideWaitDialog();
                                }

                                @Override
                                public void onFailure(Call<ShyjhxqBean> call, Throwable t) {
                                    MyToast.showFail();
                                }
                            }

                    );
                }
            });
            return convertView;
        }

        class ViewHolder {
            //月计划号
            TextView yjhh;
            //施工日期
            TextView sgrq;
            //类别
            TextView lb;
            //B类防御layout
            LinearLayout layout_blfh;
            LinearLayout tablelayout;
            //线名
            TextView xm;
            //行别
            TextView hb;
            //施工地点
            TextView sgdd;
            //施工项目
            TextView sgxm;
            //施工内容
            TextView sgnr;
            //施工机械
            TextView sgjx;
            //B类防护
            TextView blfh;
            //施工单位
            TextView sgdw;
            //状态
            TextView zt;
            //操作按钮图片
            ImageView mImageView, flagImg;
            private TextView tv_jhsh;
            TextView btnShlc;
        }
    }

    //设置搜索参数
    public  Map<String,String> setMap(  Map<String,String> map, JhshSearchBean Bean) {
        if (Bean != null) {
            if (Bean.getZt() != null) {
                if (Bean.getZt().equals("可审核")) {
                    map.put("searchState", "2");
                }
                if (Bean.getZt().equals("待审核")) {
                    map.put("searchState", "3");
                }
                if (Bean.getZt().equals("已审批")) {
                    map.put("searchState", "4");
                }
                if (Bean.getZt().equals("已超时")) {
                    map.put("searchState", "5");
                }
                if (Bean.getZt().equals("全部")) {
                    map.clear();
                }
            }
            if (Bean.getJhnyks() != null && !Bean.getJhnyks().equals("")) {
                map.put("searchStartMonth", mSearchBean.getJhnyks());
            }
            if (Bean.getJhnyjs() != null && !Bean.getJhnyjs().equals("")) {
                map.put("searchEndMonth", mSearchBean.getJhnyjs());
            }
            if (Bean.getJhh() != null && !Bean.getJhh().equals("")) {
                map.put("searchBh", mSearchBean.getJhh());
            }
            if (Bean.getDwhbmId() != null) {
//                if (!MyApplication.getmLoginUser().getUserUnitType().equals("sgb") && !MyApplication.getmLoginUser().getUserUnitType().equals("jgcs"))
                map.put("searchDwId", mSearchBean.getDwhbmId());
            }
            if (Bean.getLb() != null && !Bean.getLb().equals("")) {
                map.put("searchSgLb", mSearchBean.getLb());
            }
            if (Bean.getXm() != null && !Bean.getXm().equals("")) {
                map.put("searchXlMc", mSearchBean.getXm());
            }

            if (Bean.getSfzs() != null && !Bean.getSfzs().equals("")) {
                if (Bean.getSfzs().equals("主审")) {
                    map.put("searchSpcs", "1");
                }
                if (Bean.getSfzs().equals("非主审")) {
                    map.put("searchNotSpcs", "1");
                }
            }
        } else {
            if (DateUtil.compare2Time("05") < 0) { //显示当前本月计划
                map.put("searchStartMonth", DateUtil.getNowMonth());
                map.put("searchEndMonth", DateUtil.getNowMonth());
            } else { //显示次月计划
                map.put("searchStartMonth", DateUtil.getNextMonth());
                map.put("searchEndMonth", DateUtil.getNextMonth());
            }
        }
        return map;
    }

}